import { defineStore } from 'pinia'
import router from '@/router'
import { MENU_DATA } from '@/enums/cacheEnum'
import { createStorage } from '@/utils/storage'
import { transformTree2Arr, transformTreeData } from '@/utils/tools'

const Storage = createStorage()

export const useMenuStore = defineStore('app-menu', {
  state: () => ({
    menuList: Storage.get(MENU_DATA, [])
  }),
  actions: {
    /**
     * 设置菜单数据
     */
    setMenu(data = []) {
      this.menuList = data
      Storage.set(MENU_DATA, data, null)
    },

    /**
     * 更新菜单
     * 根据功能模块展示对应的独立菜单
     * @param   {array}  authData        权限数据
     * @param   {boolean}  isNoRequired  无需验证权限, 当为true时，不再验证权限
     */
    updateMenu(authData, isNoRequired) {
      const fullRoutes = router.getRoutes() || []
      const optionRoutes = router.options.routes || []
      const parentDataId = 'root'
      let tmpData = []
      // 将路由tree转化成一维的
      const treeRoutes = transformTree2Arr(optionRoutes) || []

      treeRoutes.map((item) => {
        const meta = item.meta || {}
        const isHasRoute = isNoRequired || authData?.filter((f) => meta.authMark?.includes(f))?.length > 0

        // hideMenu为true； 存在用户权限内的路由
        if (!meta.hideMenu && !meta.highlight && isHasRoute && item.path && item.name) {
          // 通过定义的name，从fullRoutes中获取完整的path
          const fullPathItem = fullRoutes.find((f) => f.name === item.name)

          tmpData.push({
            ...item,
            title: meta.title,
            id: item.path,
            parentId: item.parentData?.path || parentDataId,
            path: fullPathItem?.path
          })
        }
      })

      // 将处理完的一维菜单转化成tree
      const resData = transformTreeData(tmpData, 'root')
      // 根据 sortIndex 字段排序
      const sortRoutes = resData.sort((n, p) => n.meta?.sortIndex - p.meta?.sortIndex)

      this.setMenu(sortRoutes)
    }
  }
})
